<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2019/1/10
 * Time: 20:29
 */

namespace app\admin\controller;

use think\Db;
use \app\admin\model\Logistics as LogisticsModel;

class Waybill extends Main
{

    /**
     * 运单列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if (checkEntranceList()) {//总公司管理员，跳转选子公司页面
            action('admin/globalFun/choose', ['backtrack' => "index"]);
            return $this->fetch(APP_PATH . request()->module() . '/view/public/choose.html');
        }
        $company_id = iget('company_id') ? iget('company_id') : isession('company_id');
        $where['company_id'] = $company_id;
        $where1 = [];
        get('platform') && $where['platform'] = get('platform');
        get('express') && $where['express'] = ['like', '%' . get('express') . '%'];
        get('waybill') && $where['waybill'] = ['like', '%' . get('waybill') . '%'];
        get('start') && $where['timestamp'] = ['>=', strtotime(get('start') . " 00:00:00")];
        get('end') && $where1['timestamp'] = ['<=', strtotime(get('end') . " 23:59:59")];

        $waybill = Db::name('waybill')
            ->where($where)
            ->where($where1)
            ->order('timestamp desc')
            ->paginate(12, false, ['query' =>
                [
                    'express' => get('express'),
                    'waybill' => get('waybill'),
                    'start' => get('start'),
                    'end' => get('end'),
                    'platform' => get('platform'),
                    'company_id' => iget('company_id')
                ]]);
        $list = $waybill->all();
        if (checkArr($list)) {
            //获取所有运单id
            $waybill_ids = array_column($list, 'id');

            //获取运单下有图片url的商品
            $where2['url'] = ['neq', ''];
            $where2['waybill_id'] = ['in', join(',', $waybill_ids)];
            $product = Db::name('waybill_product')
                ->field('waybill_id,url')
                ->where($where2)
                ->group('waybill_id')
                ->select();
            checkArr($product) && $product = arrayCombine($product, 'waybill_id');

            //拼接订单详情url
            foreach ($list as $key => $value) {
                $list[$key] = $this->getOrderDetailUrl($value, $product);
            }
        }

        $this->assign('list', $list);
        $this->assign('waybill', $waybill);
        $this->assign('platform', $this->getDictionary('platform'));
        return $this->fetch();
    }

    /**
     * 获取运单跳转订单详情url
     * @param array $data
     * @param array $product
     * @param string $company_id
     * @return array
     */
    public function getOrderDetailUrl($data = [], $product = [])
    {
        $data['imgpath'] = isset($product[$data['id']]['url']) ? $product[$data['id']]['url'] : '';
        switch ($data['platform']) {
            case 1:
                $data['url'] = "admin/amazonorder/amazonInfo";
                break;//亚马逊店铺
            case 2:
                $data['url'] = '';
                break;//ebay店铺
            case 3:
                $data['url'] = '';
                break;//速卖通店铺
            case 4:
                $data['url'] = '';
                break;//wish店铺
        }
        return $data;
    }

    /**
     * 运单详情
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit($id)
    {
        if (post()) {
            if (checkSubmitEdit()) {
                $this->error("当前状态不允许编辑信息");
            }
            $data = post();
            //订单信息
            $order = Db::name('amazon_order')->where('id', $data['order_id'])->find();
            if (!checkArr($order)) {
                $this->error("当前订单不存在");
            }
            $carriage = $data['carriage'];

            $updateData['logistic'] = $data['logistic'];
            $updateData['logistic_id'] = $data['logistic_id'];
            $updateData['shipping_method'] = $data['shipping_method'];
            $updateData['customs'] = $data['customs'];
            $updateData['customs_en'] = $data['customs_en'];
            $updateData['express'] = $data['express'];
            $updateData['coding'] = $data['coding'];
            $updateData['waybill'] = $data['waybill'];
            $updateData['deliver'] = $data['deliver'];
            $updateData['declare_unit_id'] = $data['declare_unit_id'];
            $updateData['declare_unit'] = $data['declare_unit'];
            $updateData['declare'] = $data['declare'];
            $updateData['insure_unit_id'] = $data['insure_unit_id'];
            $updateData['insure_unit'] = $data['insure_unit'];
            $updateData['insure'] = $data['insure'];
            $updateData['fee_unit_id'] = $data['fee_unit_id'];
            $updateData['fee_unit'] = $data['fee_unit'];
            $updateData['fee'] = $data['fee'];
            $updateData['weight'] = $data['weight'];
            $updateData['is_battery'] = isset($data['is_battery']) ? $data['is_battery'] : 1;
            $updateData['remark'] = $data['remark'];

            //运费（人民币）
            $momey = 0;
            if ($data['fee'] > 0) {
                if ($data['fee_unit'] == 'CNY') {
                    $momey = $data['fee'];
                } else {
                    $rate = $this->getRate($data['fee_unit']);
                    $momey = $data['fee'] / $rate[$data['fee_unit']]['rate'];
                }
                $momey = cutNum($momey, 2);
            }
            $updateData['carriage'] = $momey;
            Db::name('waybill')->where('id', $data['id'])->update($updateData);
            if ($data['audit'] != 2) {
                $this->rechargeLog($data, $data['id']);
            }
            //总运费
            $updata['shipping_money'] = $momey + $order['shipping_money'] - $carriage;
            $updata['shipping_status'] = 3;
            //修改订单运单状态
            Db::name('amazon_order')->where('id', $data['order_id'])->update($updata);
            $this->success("更新成功");
        } else {
            //运单信息
            $waybill = Db::name('waybill')
                ->where('id', $id)
                ->find();
            //运单下的商品
            $waybillGoods = Db::name('waybill_product')
                ->where('waybill_id', $id)
                ->select();
            $this->assign('waybill', $waybill);
            $this->assign('waybillGoods', $waybillGoods);
            //货币信息
            $this->assign('unit', $this->getDictionary('unit'));
            //物流公司信息
            $logistics = arrayCombine($this->getLogistics(), 'id');
            $this->assign('logistics', $logistics);
            //配送方式
            $order = Db::name('amazon_order')->where('id', $waybill['order_id'])->find();
            if (!checkArr($order)) {
                $this->error('当前订单不存在');
            }
            $shipping = $this->getLogisticShips($waybill['logistic_id'], $order['receive_nation_short']);
            $this->assign('shipping', $shipping);
//            p($logistics);die;
            if (isession('type') == 1) {
                return $this->fetch('edit');
            }
            return $this->fetch('info');
        }
    }

    /**
     * 更新记录钱包日志
     * @param array $data
     * @param string $waybill_id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function rechargeLog($data = [], $waybill_id = '')
    {
        $company_id = isession('company_id');
        $type = isession('type');
        $purpose = $type == 1 ? 1 : 2;
        //检测充值公司钱包是否存在
        $where['company_id'] = $company_id;
        $where['purpose'] = $purpose;
        $wallet = DB::name('wallet')->where($where)->find();
        if (!checkArr($wallet)) {//不存在钱包，创建空钱包
            $insertData['money'] = 0;
            $insertData['company_id'] = $company_id;
            $insertData['type'] = $type;
            $insertData['purpose'] = $purpose;
            $insertData['timestamp'] = time();
            DB::name('wallet')->insert($insertData);
            $wallet_id = Db::name('wallet')->getLastInsID();
        } else {
            $wallet_id = $wallet['id'];
        }

        $money = $data['fee'];
        //不是人民币，需要换算单位
        if ($data['fee_unit'] != 'CNY') {
            $money = $this->toCny($money, $data['fee_unit']);
        }
        $log['money'] = $money;
        $log['remark'] = $data['remark'];

        $where1['detail_id'] = $waybill_id;
        $where1['project'] = 4;
        $where1['purpose'] = $purpose;
        $where1['operate'] = 2;
        $where1['audit'] = 1;
        $wallet_log = DB::name('wallet_log')->where($where1)->find();
        if (checkArr($wallet_log)) {//存在记录，更新
            DB::name('wallet_log')->where('id', $wallet_log['id'])->update($log);
            return true;
        }

        $log['wallet_id'] = $wallet_id;
        $log['company_id'] = $company_id;
        $log['type'] = $type;
        $log['purpose'] = $purpose;
        $log['operate'] = 2;
        $log['operate_company_id'] = $company_id;
        $log['operate_date'] = time();
        $log['reason_id'] = '';
        $log['reason'] = '运单运费';
        $log['resource_id'] = '';
        $log['project'] = 4;
        $log['detail_id'] = $waybill_id;
        $log['audit'] = 1;
        $log['operate_audit'] = $type;
        $log['operate_uid'] = isession('user_id');
        $log['operate_name'] = ssession('username');
        $log['operate_truename'] = ssession('truename');
        $log['timestamp'] = time();
        DB::name('wallet_log')->insert($log);
    }

    /**
     * 外汇换算人民币
     * @param int $money
     * @param string $unit
     * @return float|int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function toCny($money = 0, $unit = '')
    {
        if ($money == 0 || $unit == '') {
            return 0;
        }
        $rate = $this->getCNY($unit, $type = 'update');
        return $money / $rate;
    }
}